package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.enums.TaskTypeEnum;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    /**
     * 添加任务到延迟队列中
     *
     * @param wmNews
     */
    @Override
    public void addWmNewsToTask(WmNews wmNews) {
        Task task = new Task();

        task.setExecuteTime(wmNews.getPublishTime().getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        scheduleClient.addTask(task);
    }

    /**
     * 消费延迟队列数据
     */
    @Scheduled(fixedRate = 1000)
    @Override
    public void scanNewsByTask() throws Exception {
        //1. 通过Feign请求获取对应type和优先级的任务
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        //2. 如果获取成功则完成文章的审核接口
        if(null != responseResult && responseResult.getCode() == 200 && null != responseResult.getData()){
           // String jsonTask = responseResult.getData().toString();//OBJECT ->STRING _>内存地址
            String jsonTask = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(jsonTask, Task.class);

            byte[] parameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);

            //完成文章审核操作
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }
    }
}
